import json
import logging
from voice_assistant.my_state import app_state
from voice_assistant.commands.command_executor import process_command
from voice_assistant.voice.wakeword import handle_wake_word_detection

logger = logging.getLogger("VoiceAssistant")

async def handle_message(ws):
    """处理接收到的消息"""
    try:
        while True:
            message = await ws.recv()
            # logger.info(f"收到消息: {message}")
            data = json.loads(message)
            
            if data['type'] == 'full_transcript':
                text = data['text'].strip()
                if text:
                    app_state.current_transcript = text
                    logger.info(f"转写结果: {text}")
                    
                    # 唤醒状态处理
                    if app_state.waiting_for_wake:
                        handle_wake_word_detection(text)
                    elif text:
                        process_command(text)
                        app_state.silence_counter = 0
                    
    except Exception as e:
        logger.error(f"消息处理出错: {str(e)}")